package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpRole;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpSysParam;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpUserInfo;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpRoleService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpUserInfoService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.RedpUpmpUtil;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.HashUtil;
import cc.rengu.redp.common.utils.RedpUtil;
import cc.rengu.redp.system.domain.DictRsVo;
import cc.rengu.redp.system.domain.UserConfig;
import cc.rengu.redp.system.service.UserConfigService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author System
 */
@RestController
@RequestMapping("/admin/upmpuser")
@Slf4j
public class UpmpUserInfoController extends BaseController {


    @Autowired
    private IUpmpUserInfoService upmpUserInfoService;
    @Autowired
    private UserConfigService userConfigService;
    @Autowired
    private IUpmpRoleService upmpRoleService;
    @Autowired
    private IUpmpSysParamService upmpSysParamService;

    @GetMapping("check")
    public boolean checkUserName(@NotBlank(message = "{required}") String instId,
                                 @NotBlank(message = "{required}") String username) {
        return this.upmpUserInfoService.findByName(username) == null;
    }

    @GetMapping("/{instId}/{userId}")
    public UpmpUserInfoVO detail(@NotBlank(message = "{required}") @PathVariable String instId,@NotBlank(message = "{required}") @PathVariable String userId) {
        UpmpUserInfo user = this.upmpUserInfoService.findByUserId(instId,userId);
        UpmpUserInfoVO vo= new UpmpUserInfoVO();
        //修复用户修改自己的个人信息第二次提示roleId不能为空
        List<UpmpRole> roles = upmpRoleService.findUserRole(user.getId());
        List<String> roleIds = roles.stream().map(role -> role.getId()).collect(Collectors.toList());
        String roleIdStr = StringUtils.join(roleIds.toArray(new Long[roleIds.size()]), ",");
        vo.setRoleId(roleIdStr);
        return vo;
    }

    @GetMapping
//    @RequiresPermissions("user:list")
    public Map<String, Object> userList(QueryRequest queryRequest, UpmpUserInfoVO user) throws RedpException {
        log.error("queryRequest.getPageNum:{}",queryRequest.getPageNum());
        return getDataTable(upmpUserInfoService.findUserPage(user, queryRequest));
    }

    @GetMapping("getAllUsers")
    public List<DictRsVo> getAllUsers(){
        List<UpmpUserInfo> users = upmpUserInfoService.getAllUsers();
        List<DictRsVo> dictRsVos = new ArrayList<>();
        users.forEach(user -> dictRsVos.add(new DictRsVo(user.getUserName(), user.getUserName())));
        return dictRsVos;
    }

    @Log("新增用户")
    @PostMapping
//    @RequiresPermissions("user:add")
    public RedpResponse addUser(@Valid UpmpUserInfoVO user) throws RedpException {
        try {
            this.upmpUserInfoService.createUser(user);
        } catch (Exception e) {
            String message = "新增用户失败";
            log.error(message, e);
//            throw new RedpException(message);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("新增用户成功");
    }

    @Log("修改用户")
    @PutMapping
//    @RequiresPermissions("user:update")
    public RedpResponse updateUser(@Valid UpmpUserInfoVO user) throws RedpException {
        try {
            this.upmpUserInfoService.updateUser(user);
        } catch (Exception e) {
            String message = "修改用户失败";
            log.error(message, e);
//            throw new RedpException(message);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("修改用户成功");
    }

    @Log("删除用户")
    @DeleteMapping("/{userIds}")
//    @RequiresPermissions("user:delete")
    public RedpResponse deleteUsers(@NotBlank(message = "{required}") @PathVariable String userIds) throws RedpException {
        try {
            String[] ids = userIds.split(StringPool.COMMA);
            this.upmpUserInfoService.deleteUsers(ids);
        } catch (Exception e) {
            String message = "删除用户失败";
            log.error(message, e);
//            throw new RedpException(message);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("删除用户成功");
    }

    @PutMapping("profile")
    public RedpResponse updateProfile(@Valid UpmpUserInfo user) throws RedpException {
        try {
            this.upmpUserInfoService.updateProfile(user);
        } catch (Exception e) {
            String message = "修改个人信息失败";
            log.error(message, e);
//            throw new RedpException(message);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("修改个人信息成功");
    }

    @PutMapping("avatar")
    public RedpResponse updateAvatar(
            @NotBlank(message = "{required}") String username,
            @NotBlank(message = "{required}") String avatar) throws RedpException {
        try {
            this.upmpUserInfoService.updateAvatar(username, avatar);
        } catch (Exception e) {
            String message = "修改头像失败";
            log.error(message, e);
//            throw new RedpException(message);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("修改头像成功");
    }

    @PutMapping("userconfig")
    public RedpResponse updateUserConfig(@Valid UserConfig userConfig) throws RedpException {
        try {
            this.userConfigService.update(userConfig);
        } catch (Exception e) {
            String message = "修改个性化配置失败";
            log.error(message, e);
//            throw new RedpException(message);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("修改个性化配置成功");
    }

    @GetMapping("password/check")
    public boolean checkPassword(
            @NotBlank(message = "{required}") String password) {
        UpmpSysParam defaultInst = upmpSysParamService.getById(UpmpConstant.DEAFULT_INST_PARAM_ID);
        String username = RedpUpmpUtil.getCurrentUser(defaultInst.getPrimaryValue()).getUserName();
        String encryptPassword = HashUtil.encryptGm(username, password);
        UpmpUserInfo user = upmpUserInfoService.findByName(username);
        if (user != null)
            return StringUtils.equals(user.getLoginPassword(), encryptPassword);
        else
            return false;
    }

    @PutMapping("password")
    public RedpResponse updatePassword(
            @NotBlank(message = "{required}") String oldPassword,
            @NotBlank(message = "{required}") String newPassword) throws RedpException {
        if (this.checkPassword(oldPassword)) {
        try {
                UpmpSysParam defaultInst = upmpSysParamService.getById(UpmpConstant.DEAFULT_INST_PARAM_ID);
                String username = RedpUpmpUtil.getCurrentUser(defaultInst.getPrimaryValue()).getUserName();
                upmpUserInfoService.updatePassword(username, newPassword);
            } catch (Exception e) {
                String message = "修改密码失败";
                log.error(message, e);
//            throw new RedpException(message);
                return RedpResponse.getInstance().failure().message(message);
            }
        } else {
            String message = "修改密码失败";
            log.error(message);
            return RedpResponse.getInstance().failure().message(message);
        }

        return RedpResponse.getInstance().success().message("修改密码成功");
    }

    @PutMapping("password/reset")
    @RequiresPermissions("user:reset")
    public RedpResponse resetPassword(@NotBlank(message = "{required}") String ids) throws RedpException {
        try {
            String[] idArr = ids.split(StringPool.COMMA);
            this.upmpUserInfoService.resetPassword(idArr);
        } catch (Exception e) {
            String message = "重置用户密码失败";
            log.error(message, e);
//            throw new RedpException(message);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("重置用户密码成功");
    }

    @PostMapping("excel")
    @RequiresPermissions("user:export")
    public RedpResponse export(QueryRequest queryRequest, UpmpUserInfoVO user, HttpServletResponse response) throws RedpException {
        try {
            List<UpmpUserInfoVO> users = this.upmpUserInfoService.findUserPage(user, queryRequest).getRecords();
            ExcelKit.$Export(UpmpUserInfo.class, response).downXlsx(users, false);
        } catch (Exception e) {
            String message = "用户信息导出Excel失败";
            log.error(message, e);
//            throw new RedpException(message);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("用户信息导出Excel成功");
    }



    //@PathVariable的传参方式不支持中文，否则前端会报 Cross-origin resource sharing error: PreflightInvalidstatus  的异常
//    @GetMapping("queryUserByLoginId/{instId}/{loginId}")
    @GetMapping("queryUserByLoginId")
    public List<UpmpUserInfo> queryUserByLoginId(@NotBlank(message = "{required}") String instId,@NotBlank(message = "{required}")  String loginId) {
        return this.upmpUserInfoService.queryUserByLoginId(instId,loginId);
    }
}
